'use strict';

import React, {Component, PropTypes} from 'react';
import ReactDOM, {render} from 'react-dom';
import {connect} from 'react-redux';
import {
    hashHistory
} from 'react-router'
import {bindActionCreators} from 'redux';

import {R_header} from './common/index'
import {HttpService, Toast} from '../Http';
import DatePicker from '../Component/DatePicker/DatePicker3'

import move from '../img/move.png'
import endMove from '../img/endMove.png'
import startMove from '../img/startMove.png'
import roadMove from '../img/roadMove.png'
import mapInfoWin from '../img/mapInfoWin.png'
import imgBo from '../img/bo.png'
import imgZn from '../img/zn.png'

export default class About extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: null,
            map: [],
            speed: '中',
            bo: '',
            progress: '0%',
            disabled: 'disabled',
            addressArray: [],
            viewProgress:false,
            lineArrLength: 0,//为1的时候不能查看历史轨迹
        };
        this.mapObj;
        this.markers;
        this.lineArr = [];
        this.lineArrs = [];
        this.mklineArr = [];
        this.position = 0;
        this.mrkLength = 0;
        this.speed = 500;
        this.polylines = [];//所有画的线
        this.markerRecs = [];//递归是在地图添加的点-所有的
        this.distance = 0;//所有点的距离
        this.lastPointdistance = 0;//上一个点的距离
        this.progressBar = 0;//划线的下标
        this.passedPath;//暂停的时候开始点变化了，所以用改变量那开始的位置记录下拉然后赋值
        this.lastPolylineStop = [];//停止的时候画的线-上一级
        this.newPolylineStop = [];//停止的时候画的线-这一级
        this.pointArray=[];//查询的坐标
        this.newPolyLine ="";//查询的坐标
        this.infoWindow ="";//信息窗体

    }

    /**
     * 在渲染前调用,在客户端也在服务端。
     */
    componentWillMount() {
        this.getHistoryTracks(this.props.params.babyid, this.timeStamp2String(0), this.timeStamp2String(1))
    }
    /**
     * 在组件从 DOM 中移除的时候立刻被调用。
     */
    componentWillUnmount() {
        this.mapObj.clearMap();
    }

    /**
     * 改变日期
     * @param value 时间
     */
    handleValChange(value) {
        this.polylines = [];
        this.markerRecs = [];
        let newValue = this.timeStamp2String(0);//后一天的时间 今天的时间
        const valueShow = this.timeStamp2String(0, this.state.value);//前一天的时间
        newValue = newValue.replace(/\-/g, "\/");
        if(this.infoWindow != "" && this.infoWindow != null){
            this.infoWindow.close();//关闭信息窗体
        }
        if ((value.replace(/\-/g, "\/") == newValue && valueShow.replace(/\-/g, "\/") == newValue) || value.replace(/\-/g, "\/") == valueShow.replace(/\-/g, "\/")) {
            this.setState({disabled: 'disabled', progress: '0%', bo: ''});
            return;
        }if (new Date(value.replace(/\-/g, "\/")) == new Date(newValue)) {
            this.setState({disabled: 'disabled', progress: '0%', bo: ''});
        }else if(new Date(value.replace(/\-/g, "\/")) < new Date(newValue)){
            this.setState({disabled: '', progress: '0%', bo: ''});
        }
        this.lastPointdistance = 0;//上一个点的距离制空
        this.progressBar = 0;//上一个点的进度条制空
        if(this.mklineArr.length == undefined){
            this.mklineArr.pauseMove(); //暂停动画
        }else{
            this.moveAlongs();
        }
        this.setState({
            progress: '0%',
            bo: '',
        });
        this.mapObj.clearMap();
        this.refs.setTimeValue.setDatePickerValue(value);
        this.mapObj.remove(this.mklineArr);//移除所有的点-初始化的点
        this.mapObj.remove(this.lastPolylineStop);
        this.mapObj.remove(this.newPolylineStop);
        this.mapObj.remove(this.polylines);//移除所有的线
        this.mapObj.remove(this.markerRecs);//移除所有的点-移动时添加
        // rct.markerRec.setMap(rct.mapObj);
        this.setState({
            progress: '0%',
        });
        this.getHistoryTracks(this.props.params.babyid, value, value.substring(0, 8).concat(parseInt(value.substring(8, 10)) + 1).toString())
    }

    /**
     * 前一天
     */
    agoDay() {
        const value = this.timeStamp2String(-1, this.state.value);//前一天的时间
        this.setState({disabled: '', progress: '0%', bo: ''});
        this.handleValChange(value);
    }

    /**
     * 后一天
     */
    afterDay() {
        let value = this.timeStamp2String(1, this.state.value), newValue = this.timeStamp2String(0);//后一天的时间 今天的时间
        value = value.replace(/\-/g, "\/");
        newValue = newValue.replace(/\-/g, "\/");
        if (value == newValue) {
            this.setState({disabled: 'disabled', progress: '0%', bo: ''});
            this.handleValChange(this.timeStamp2String(1, this.state.value));
        }else if (new Date(value) == new Date(newValue)) {
            this.setState({disabled: 'disabled', progress: '0%', bo: ''});
            this.handleValChange(this.timeStamp2String(1, this.state.value));
        }else if(new Date(value) < new Date(newValue)){
            this.setState({disabled: '', progress: '0%', bo: ''});
            this.handleValChange(this.timeStamp2String(1, this.state.value));
        }else{
            this.setState({disabled: 'disabled', progress: '0%', bo: ''});
        }
    }

    /**
     * 点击开始播放轨迹
     * 或者停止播放轨迹
     */
    moveAlongs(){
        let rct = this;
        if(rct.pointArray.length == 0){
            return;
        }
        //返回的坐标只有一个
        if(rct.state.lineArrLength==1){
            return;
        }
        if(rct.infoWindow != "" && rct.infoWindow != null){
            rct.infoWindow.close();//关闭信息窗体
        }
        if (rct.state.bo == '') {
            rct.setState({bo: 'zn'});
            const progress = parseFloat(rct.refs.progress.style.width);//此时进度条的长度
            if (progress > 0 && progress < 100) {
                rct.mklineArr.resumeMove(); //继续动画
                return;
            }else{
                rct.markerRecs = [];
                rct.mapObj.remove(rct.mklineArr);//移除所有的点-初始化的点
                rct.mapObj.remove(rct.lastPolylineStop);
                rct.mapObj.remove(rct.newPolylineStop);
                rct.mapObj.remove(rct.polylines);//移除所有的线
                rct.mapObj.remove(rct.markerRecs);//移除所有的点-移动时添加
                // rct.markerRec.setMap(rct.mapObj);
                rct.setState({
                    progress: '0%',
                });
               let newMarkerRec = new AMap.Marker({
                    map: rct.mapObj,
                    icon: startMove,
                    position: [rct.lineArr[0][0], rct.lineArr[0][1]]
                });
                newMarkerRec.on('click', rct.markerClick.bind(rct,[[rct.pointArray[0].lng, rct.pointArray[0].lat],rct.pointArray[0].gpstime]));
                rct.markerRecs.push(newMarkerRec);
                rct.passedPath = {J:rct.lineArr[0][0],N:rct.lineArr[0][1],lat:rct.lineArr[0][0],lng:rct.lineArr[1][0]};
                rct.moveIndex = 0;
                rct.moveToRecursion(0);
            }
        }else{
            rct.stopMove();
        }
    }

    /**
     * 停止移动
     */
    stopMove(){
        let rct = this;
        rct.setState({bo: ''});
        if(this.mklineArr.length == undefined){
            rct.mklineArr.pauseMove(); //暂停动画
        }
        //暂停后-开始会从停留的地方开始，所以需要划线 开始点-暂停点的线
       let stopPolyLine = new AMap.Polyline({
            map:  rct.mapObj,
            path: [[rct.passedPath.J, rct.passedPath.N],[rct.passedPath.lng,rct.passedPath.lat]],
            strokeColor: "#01b4ee",  //线颜色
            strokeOpacity: 1,     //线透明度
            strokeWeight: 3,      //线宽
            strokeStyle: "solid"  //线样式
        });
       rct.newPolylineStop.push(stopPolyLine);

    }
    /**
     * 递归-划线
     *  @param index 经纬度下标
     */
    moveToRecursion(index){
        let rct = this;
        rct.newPolyLine = '';
        let lat = rct.lineArr[index][0],lng = rct.lineArr[index][1],latNext = rct.lineArr[index+1][0],lngNest = rct.lineArr[index+1][1];
        //绘制轨迹的坐标
        rct.mklineArr = new AMap.Marker({
            map: rct.mapObj,
            position: [lat, lng],
            icon: new AMap.Icon({
                size: new AMap.Size(3, 3),  //图标大小
                image: roadMove,
                imageOffset: new AMap.Pixel(0, -60)
            })
            // autoRotation: true
        });
        // 绘制轨迹
        rct.newPolyLine = new AMap.Polyline({
            map:  rct.mapObj,
            // path: [ [lat, lng],[latNext, lngNest]],//每次加载的时候会闪烁一下
            strokeColor: "#01b4ee",  //线颜色
            strokeOpacity: 1,     //线透明度
            strokeWeight: 3,      //线宽
            strokeStyle: "solid"  //线样式
        });
        /**
         * 划线方法
         *  @param value1 传入一个点
         *  @param value2 速度
         *  @param value3 函数 需要return k
         */
        rct.mklineArr.moveTo( new AMap.LngLat(latNext,lngNest),rct.speed);
        //移动回调函数
        rct.mklineArr.on('moving',function(e){
            let moveNextLat = e.passedPath[1].lat,moveNextLng = e.passedPath[1].lng;
            rct.passedPath.lat = moveNextLat;
            rct.passedPath.lng = moveNextLng;
            let moveDistance = new AMap.LngLat(rct.passedPath.J,rct.passedPath.N).distance([moveNextLng, moveNextLat]);//计算两点之间的距离
            rct.progressBar += (parseFloat((moveDistance+"").substring(0,(moveDistance+"").indexOf('.')+7))-rct.lastPointdistance)/rct.distance*100;//计算滚动条宽度
            rct.lastPointdistance = parseFloat((moveDistance+"").substring(0,(moveDistance+"").indexOf('.')+7));//记录上一次距离
            rct.setState({progress: ''+rct.progressBar+'%'});
            rct.newPolyLine.setPath(e.passedPath);
        });
        //缩放地图大小停止动画
        rct.mapObj.on('zoomchange',function (e) {
            rct.stopMove();
        });
        //一个动画结束后
        rct.mklineArr.on('moveend', function() {
            rct.lastPointdistance = 0;//上一个点的距离制空
            if(rct.lineArr.length-2 == index){
                rct.polylines.push(rct.newPolyLine);
                rct.progressBar = 0;//上一个点的进度条制空
                rct.mapObj.remove(rct.mklineArr);//移除所有的点-初始化的点
                rct.mapObj.remove(rct.polylines);//移除所有的线
                rct.mapObj.remove(rct.markerRecs);//移除所有的点-移动时添加
                rct.mapObj.remove(rct.lastPolylineStop);
                rct.mapObj.remove(rct.newPolylineStop);
                if(rct.infoWindow != "" && rct.infoWindow != null){
                    rct.infoWindow.close();//关闭信息窗体
                }
                rct.setState({
                    progress: '0%',//滚动条
                    bo: ''//是否播放
                });
                //一个动画播放完后回到最初
                rct.mklineArr = [];
                rct.pointArray.forEach(function(point) {
                    let mk = new AMap.Marker({
                        map: rct.mapObj,
                        icon: move,
                        zIndex: point.zIndex,
                        position: [
                            point.lng, point.lat
                        ],
                        autoRotation: true,
                        // offset: new AMap.Pixel(-12, -40)
                    });
                    mk.on('click', rct.markerClick.bind(rct,[[point.lng, point.lat],point.gpstime]));
                    rct.mklineArr.push(mk);
                });
                rct.polylines = [];
                return;
            }
            rct.passedPath = {J:latNext,N:lngNest,lat:latNext.toFixed(6),lng:lngNest.toFixed(6)};
            let newMarkerRec = new AMap.Marker({
                icon: move,
                position: [latNext, lngNest]
            });
            newMarkerRec.on('click', rct.markerClick.bind(rct,[[rct.pointArray[index+1].lng, rct.pointArray[index+1].lat],rct.pointArray[index+1].gpstime]));
            newMarkerRec.setMap(rct.mapObj);
            rct.markerRecs.push(newMarkerRec);
            rct.polylines.push(rct.newPolyLine);
            if(index > 0){
                rct.mapObj.remove(rct.polylines[index-1]);
                rct.mapObj.remove(rct.markerRecs[index-1]);
                if(rct.lastPolylineStop.length > 0){
                    for(let i = 0;i < rct.lastPolylineStop.length;i++){
                        rct.mapObj.remove(rct.lastPolylineStop[i]);
                    }
                    rct.lastPolylineStop = [];
                }
            }
            rct.lastPolylineStop = rct.newPolylineStop;
            rct.newPolylineStop = [];
            rct.moveToRecursion(index+1);
        });
    }

    /**
     *  点击点出现信息窗体
     * @param info 点 时间
     */
    markerClick(info){
        let rct = this,formattedAddress = '';
        if(rct.infoWindow != "" && rct.infoWindow != null){
            rct.infoWindow.close();//关闭信息窗体
        }
        const progress = parseFloat(rct.refs.progress.style.width);//此时进度条的长度
        if (progress > 0 && progress < 100) {
            rct.stopMove(); //暂停动画
        }
        let geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
        });
        //获取地址
        geocoder.getAddress(info[0], function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                formattedAddress = result.regeocode.formattedAddress;
                rct.infoWindow = new AMap.InfoWindow({
                    isCustom: true,  //使用自定义窗体
                    content: rct.createInfoWindow(formattedAddress,info[1]),
                    offset: new AMap.Pixel(0, -46)//偏移
                });
                rct.infoWindow.open(rct.mapObj, info[0]);
            }
        });
    }
    /**
     * 信息窗体-自定义样式
     *  @param addres 地址
     *  @param gpstime 定为时间
     */
    createInfoWindow(addres,gpstime){
        let content = [];
        console.log(gpstime);
        content.push("<span class='mapInfoWinAddress'>"+addres+"</span><span class='mapInfoWinTime'>"+gpstime+"</span>");
        let info = document.createElement("div");
        info.className = "mapInfoWin";
        //可以通过下面的方式修改自定义窗体的宽高
        //info.style.width = "400px";

        // 定义中部内容
        let middle = document.createElement("div");
        middle.className = "mapInfoWin-middle";
        middle.style.backgroundColor = 'white';
        middle.innerHTML = content;
        info.appendChild(middle);

        // 定义底部内容
        let bottom = document.createElement("div");
        bottom.className = "mapInfoWin-bottom";
        bottom.style.position = 'relative';
        bottom.style.top = '0px';
        bottom.style.margin = '0 auto';
        let sharp = document.createElement("img");
        sharp.src = mapInfoWin;
        bottom.appendChild(sharp);
        info.appendChild(bottom);
        return info;
    }

    /**
     * 轨迹播放速度
     */
    moveSpeed() {
        let rct = this;
        if(rct.pointArray.length == 0){
            return;
        }
        let speed = this.state.speed;
        switch (speed) {
            case '快':
                speed = '中';
                rct.speed = 500;
                break;
            case '中':
                speed = '慢';
                rct.speed = 240;
                break;
            case '慢':
                speed = '快';
                rct.speed = 1000;
                break;
            default:
                break;
        }
        rct.setState({speed});
    }
    /**
     * 获取当前时间
     * @param time
     * @param newtime
     * @returns {string}
     */
    timeStamp2String(time, newtime) {
        var datetime = new Date();
        if (newtime)
            datetime = new Date(newtime);

        datetime.setDate(datetime.getDate() + time);
        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10
            ? "0" + (datetime.getMonth() + 1)
            : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10
            ? "0" + datetime.getDate()
            : datetime.getDate();
        var hour = '00';
        var minute = '00';
        var second = '00';
        return year + "-" + month + "-" + date;
    }
    /**
     * 查询设备一段时间里所有坐标
     * @param babyid 设备id
     * @param time1 开始时间
     * @param time2 结束时间
     */
    getHistoryTracks(babyid, time1, time2) {
        let rct = this;
        this.setState({value: time1});
        rct.pointArray = [];
        //localStorage.appToken = 'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4NzU2IiwiaWF0IjoxNDk1MTc2Mjg3LCJzdWIiOiJBaXJsaW5lIiwiaXNzIjoiMTM4NjgxMTMyMjkiLCJhdWQiOiJndWFyZGlhbiJ9.cMD_5T6b9pTwAXprbs_DgohoRyAd7H4hYYwtXVX126c'
        HttpService.query({
            url: '/app/map/getHistoryTracks',
            data: {
                token: localStorage.appToken,
                babyid: babyid,
                starttime: time1,
                endtime: time2,
                weixinclient: 'true'
            },
            success: (res => {
                if (res.code == 10062) {
                    this.setState({viewProgress:true});
                    let list = res.data;
                    let markers = [];
                    let lng = {};
                    let lat = {};
                    let _arry = [];
                    let json = {};
                    let listLenght = list.length-1;
                    rct.mklineArr = [];
                    rct.lineArr = [];
                    for(let index = 0;index < list.length;index++){
                        let item = list[index];
                        if(index > 0){
                            if(list[index-1].lng == item.lng && list[index-1].lat == item.lat){
                                listLenght --;
                                continue;
                            }
                            let lnglat = new AMap.LngLat(list[index-1].lng, list[index-1].lat);
                            rct.distance += lnglat.distance([item.lng, item.lat]);//计算路程距离
                        }
                        if (index == 0) {
                            _arry.push({lng: item.lng, lat: item.lat, img: startMove,zIndex:102,gpstime:item.gpstime});
                        }else {
                            _arry.push({lng: item.lng, lat: item.lat, img: move,zIndex:101,gpstime:item.gpstime});
                        }
                        rct.state.addressArray.push([item.lng, item.lat]);
                        rct.lineArr.push([item.lng, item.lat]);//轨迹点的数组
                    }
                    this.setState({lineArrLength:rct.lineArr.length});
                    if(rct.lineArr.length==1){
                        Toast.toast('只有一个坐标无法显示轨迹信息');
                    }
                    this.mapObj = new AMap.Map("abc", {
                        zoom: 18,
                        zoomEnable: true,
                        resizeEnable: true
                    });
                    _arry[_arry.length-1].img = endMove;//最后一个位置图标
                    _arry[_arry.length-1].zIndex = 103;//最后一个位置至于顶层
                    rct.setState({addressArray:rct.state.addressArray});//所有的坐标点
                    rct.mrkLength = _arry.length;
                    rct.pointArray = _arry;
                    //在地图上标记点
                    _arry.forEach(function(point) {
                        let mk = new AMap.Marker({
                            map: rct.mapObj,
                            icon: point.img,
                            zIndex: point.zIndex,
                            position: [
                                point.lng, point.lat
                            ],
                            autoRotation: true,
                            // offset: new AMap.Pixel(-12, -40)
                        });
                        mk.on('click', rct.markerClick.bind(rct,[[point.lng, point.lat],point.gpstime]));
                        rct.mklineArr.push(mk);
                    });
                    rct.mapObj.setFitView();
                } else {
                    this.setState({viewProgress:false});
                    Toast.toast('无轨迹信息');
                    this.mapObj = new AMap.Map("abc", {
                        zoom: 18,
                        resizeEnable: true
                    });
                }
            })
        })
    }

    /**
     * 返回上一页前暂停动画
     */
    goReturn(){
        if(this.state.bo != ''){
            this.mklineArr.pauseMove(); //暂停动画
        }
        hashHistory.goBack(-1);
    }
    render() {
        const time = this.timeStamp2String(0);
        const {speed, bo, progress, disabled,viewProgress,lineArrLength} = this.state;
        return (
            <div style={{paddingTop: '88px'}}>
                <R_header addFn={this.goReturn.bind(this)} title="历史轨迹" left="1"/>
                <div id="abc" className='mapguiji'></div>
                <div className="cde">
                    <div className='ding ago' onClick={this.agoDay.bind(this)}>前一天</div>
                    <div className={'ding after ' + disabled} onClick={this.afterDay.bind(this)}>后一天</div>
                    <DatePicker maxDate="2017-5-23" ref="setTimeValue"  onChange={this.handleValChange.bind(this)} date='2017-05-26'/>
                </div>
                {
                    viewProgress==true?
                        lineArrLength>1?
                            <div className='mappath'>
                                <label className={'bo ' + bo} onClick={this.moveAlongs.bind(this)}/>
                                <div className='time'>
                                    <div className='progress' id='progress' ref='progress' style={{width: progress}}></div>
                                </div>
                                <label className='su' onClick={this.moveSpeed.bind(this)}>{speed}</label>
                            </div>
                        :''
                    :''
                }

            </div>
        )
    }
}
